package com.didispace.hystrixCollapser;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;

import java.util.List;
// 第一步，为请求合并的实现准备一个批量请求命令的实现
public class UserBatchCommand extends HystrixCommand<List<User>> {

    UserService userService;
    List<Long> userIds;

    public UserBatchCommand(UserService userService, List<Long> userIds) {
        // super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userServiceCommand")));
        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("UserBatchCommand")).
                andCommandKey(HystrixCommandKey.Factory.asKey("UserBachKey")));
        this.userIds = userIds;
        this.userService = userService;
    }

    // 批量请求命令实际上就是一个简单的 HystrixCommand 实现，
    // 从上面的实现中可以看到它通过调用 userService.findAll 方法来访问 /users?ids={ids} 接口以返回 User 的列表结果
    @Override
    protected List<User> run() throws Exception {
        return userService.findAll(userIds);
    }
}
